<?php

	/*
	 * Show stats from mycase plugin, is called from pages/stats.php
	 * 
	 * */

	//Initialize tags and viewed practices counts
	$totalViews = 0;
	$totalTags = 0;
	$totalMycase = 0;
	$totalRates = 0;
	$distintTags = array();
	$distintTagsAux1 = array();
	$distintTagsAux2 = array();

	//Check if exist object mycase to compute stats
	if((get_subtype_id('object', 'mycase') != FALSE)){
		
		//Get all mycase object from BD
		$mycaseSubtype = get_subtype_id('object', 'mycase');
		$query = "SELECT count(guid) AS total FROM " . $CONFIG->dbprefix ."entities WHERE subtype={$mycaseSubtype}";
		$result = get_data_row($query);
		$totalMycase = $result->total;

		//Get comment/rates/views/tags objects instances from BD 
		$totalComments = count_annotations(0, 'object', 'mycase', 'generic_comment');
		$totalRates = count_annotations(0, 'object', 'mycase', 'generic_rate');

		//Get guid from mycase object with views
		$query = "SELECT e.guid FROM " . $CONFIG->dbprefix . "metadata AS m JOIN " . $CONFIG->dbprefix . "entities e ON e.guid = m.entity_guid  JOIN " . $CONFIG->dbprefix . "entity_subtypes st ON e.subtype=st.id AND st.subtype='mycase' JOIN " . $CONFIG->dbprefix . "metastrings ms ON ms.id = m.name_id WHERE ms.string = 'views'";
		$result = get_data($query);


		//For each mycase object entity
		foreach ($result AS $anGuid){
			
				$entidad = get_entity($anGuid->guid);

				//Check if a entity has tags
				if($entidad->tags){
					
					$nTags = count($entidad->tags);
					
					if($nTags == 1){	
						//Separate tags joined by ;
						$totalTags += count ($distintTagsAux1=explode(";", $entidad->tags));
						//Save distint tags to count them
						$distintTagsAux2 = array_merge($distintTagsAux1,$distintTagsAux2);
							
					}
					else{
						$totalTags += $nTags;
						foreach($entidad->tags AS $aTag){
							array_push($distintTags, $aTag);					
						}
					}
				}
				$totalViews +=  $entidad->views;
				
			}
		$distintTags = array_merge($distintTags,$distintTagsAux2);
	}


		
		

	?>
	<p>
		<br />
		<?php echo elgg_echo('mycase:statsPractices'); echo $totalMycase; ?><br />	
		<?php echo elgg_echo('mycase:statsRates'); echo $totalRates; ?><br />
		<?php echo elgg_echo('mycase:statsTotalViews'); echo $totalViews; ?><br />
		<?php echo elgg_echo('mycase:statsAverageViews'); 	echo round($totalViews/$totalMycase); ?><br />
		
		
	<?php 
	if ($totalTags) {
	?>
		 <?php echo elgg_echo('mycase:statsTags'); echo $totalTags; ?><br />
		 <?php echo elgg_echo('mycase:statsUniqueTags'); echo count( array_unique($distintTags)); ?><br />
		
	<?php
	}
	?>
	</p>
